from mootdx.quotes import Quotes
from mootdx.tools.reversion import reversion, _reversion
from db.save import Save
from db.read import DBReader
from datetime import datetime
import traceback

client = Quotes.factory(market='std')
pricetype = "2" #1-不复权，2-后复权，3-前复权
begin="2025-07-11" #包括，时间范围最少要两个交易日
end="2025-07-18" #不包括
offset=10 # 往回几个交易日
date_format = "%Y-%m-%d"
date_begin = datetime.strptime(begin, date_format)
stockcode="002456"
stockname = ""
# 读取股票列表
read = DBReader()
stocklist=read.get_stock_list()

save = Save()
conn=save.connect()
cursor = conn.cursor()

for item in stocklist:
    try:
        stockcode = item[0]
        stockname = item[1]
        # if '指数' not in stockname:
        #     continue
        need_reload = False
        # 1 先读取除权除息数据 TODO 改成去本地数据库读取
        xdxr_data = client.xdxr(symbol=stockcode)
        for index_value, row_series in xdxr_data.iterrows():
            row_dict = row_series.to_dict()
            month = row_dict['month']
            day = row_dict['day']
            year = row_dict['year']
            date_xdxr = datetime.strptime(str(year)+"-"+str(month)+"-"+str(day), date_format)
            if date_xdxr >= date_begin:
                need_reload = True
                print(f"时间范围发生除权除息事件，重新拉取该股票全量后复权数据。")
        # 2 如果有新的除权除息数据则重跑该股票的数据使用最新复权因子
        if need_reload:
            # 后复权，随便给个很早的时间，拉取全量数据
            hfq_data = client.k(symbol=stockcode, begin="1990-1-1", end=end,adjust='hfq')
            print(hfq_data.to_string())
            # 将DataFrame的每一行转换为包含索引值的字典，存放在一个列表中
            for index_value, row_series in hfq_data.iterrows():
                row_dict = row_series.to_dict()
                month = index_value.month
                day = index_value.day
                week = index_value.week
                monthstr = str(month)
                daystr = str(day)
                if month < 10:
                    monthstr = '0' + str(month)
                if day < 10:
                    daystr = '0' + str(day)
                row_dict['year'] = index_value.year
                row_dict['month'] = month
                row_dict['day'] = day
                row_dict['week'] = week
                row_dict['date'] = str(index_value.year) + '-' + monthstr + '-' + daystr
                row_dict['datetime'] = row_dict['date'] + "T15:00:00"
                row_dict['id'] = str(index_value.year) + monthstr + daystr + pricetype + stockcode
                row_dict['stockcode'] = stockcode
                row_dict['stockname'] = stockname
                row_dict.pop('vol', None)
                row_dict.pop('code', None)
                if 'vol' in row_dict:
                    del row_dict['vol']
                    print('del vol')
                if 'code' in row_dict:
                    del row_dict['code']
                    print('del code')
                save.exec(row_dict, "stock_day_info", conn, cursor)

            print("save success: " + stockcode + stockname)
        # 3 如果没有新的除权除息数据则使用库里旧的复权因子
        else:
            # 不复权 只能查股票
            bfq_data = client.k(symbol=stockcode, begin=begin, end=end)
            if bfq_data.size == 0:
                # 只能查指数
                print('查指数'+stockcode+stockname)
                bfq_data = client.index(frequency=9, symbol=stockcode, start=0, offset=offset)
            factor=read.get_stock_factor(stockcode)
            # 将DataFrame的每一行转换为包含索引值的字典，存放在一个列表中
            for index_value, row_series in bfq_data.iterrows():
                row_dict = row_series.to_dict()
                month=index_value.month
                day=index_value.day
                week = index_value.week
                monthstr = str(month)
                daystr = str(day)
                if month < 10:
                    monthstr='0'+str(month)
                if day < 10:
                    daystr = '0'+str(day)
                row_dict['year'] = index_value.year
                row_dict['month'] = month
                row_dict['day'] = day
                row_dict['week'] = week
                row_dict['date'] = str(index_value.year)+'-'+monthstr+'-'+daystr
                row_dict['datetime'] = row_dict['date'] + "T15:00:00"
                row_dict['id']=str(index_value.year) + monthstr + daystr + pricetype + stockcode
                row_dict['stockcode'] = stockcode
                row_dict['stockname'] = stockname
                if factor == 0 :
                    factor = 1
                row_dict['open'] = row_dict['open']*factor
                row_dict['close'] = row_dict['close'] * factor
                row_dict['high'] = row_dict['high'] * factor
                row_dict['low'] = row_dict['low'] * factor
                row_dict['factor'] =  factor
                row_dict.pop('vol', None)
                row_dict.pop('code', None)
                if 'vol' in row_dict:
                    del row_dict['vol']
                    print('del vol')
                if 'code' in row_dict:
                    del row_dict['code']
                    print('del code')
                save.exec(row_dict, "stock_day_info", conn, cursor)
            now = datetime.now()
            print(str(now)+":update success: "+ stockcode +stockname)
    except:
        print("error stockcode:" + stockcode)
        with open('update_error_stockcode2_list.txt', 'a+', encoding='utf-8') as f2:
            f2.writelines(stockcode+","+stockname+"\n")
            f2.close()
        traceback.print_exc()
        conn.rollback()
cursor.close()
conn.close()
